//
//  SetRatePosChannelVM.swift
//  kxf
//
//  Created by LNS2 on 2024/6/16.
//

import Foundation
import UIKit

class SetRatePosChannelVM: UIView {
    
    var channelArray = NSArray()
    var vmDataArray:[SetRatePosChannelItemVM] = [SetRatePosChannelItemVM]()
    var tapBlock:((String)->())?
    
    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: 0, y: frame.origin.y, width: SCREEN_WIDHT, height: SetRatePosChannelItemVM().selfHeight+kFitWidth(4)))
        self.backgroundColor = .white
        self.isUserInteractionEnabled = true
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension SetRatePosChannelVM{
    func setChannelDataArray(array:NSArray) {
        self.channelArray = array
        for i in 0..<array.count{
            let dict = array[i]as? NSDictionary ?? [:]
            let vm = SetRatePosChannelItemVM.init(frame: CGRect.init(x: kFitWidth(20)+SetRatePosChannelItemVM().selfHeight*CGFloat(i), y: kFitWidth(2), width: 0, height: 0))
            vm.imgView.setImgUrl(urlString: dict["icon"]as? String ?? "")
            vm.titleLab.text = dict["name"]as? String ?? ""
            
            self.addSubview(vm)
            vmDataArray.append(vm)
            
            if i == 0 {
                vm.setSelectStatus(isSelect: true)
            }else{
                vm.setSelectStatus(isSelect: false)
            }
            
//            vm.tag = 1070 + i
            vm.tapBlock = {()in
                self.selectChannel(index: i)
            }
        }
    }
    
    @objc func selectChannel(index:Int){
        for vm in vmDataArray{
            vm.setSelectStatus(isSelect: false)
        }
        let tapVm = vmDataArray[index]
        tapVm.setSelectStatus(isSelect: true)
        
        if self.tapBlock != nil{
            let dict = self.channelArray[index]as? NSDictionary ?? [:]
            self.tapBlock!(dict["code"]as? String ?? "ys")
        }
    }
}
